﻿using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using NPOI.XWPF.UserModel;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using System.Windows.Forms;

namespace Net20
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void nPOIToolStripMenuItem_Click(object sender, EventArgs e)
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("姓名");
            dt.Columns.Add("地址");
            var row = dt.NewRow();
            row["姓名"] = "令狐冲";
            row["地址"] = "金庸武侠宇宙华山思过崖";
            dt.Rows.Add(row);

            row = dt.NewRow();
            row["姓名"] = "伍六七";
            row["地址"] = "何小疯漫画宇宙理发店";
            dt.Rows.Add(row);
            ExportExcel(dt);
        }
        protected void ExportExcel(DataTable dt)
        {
            //HttpContext curContext = HttpContext.Current;
            //设置编码及附件格式
            //curContext.Response.ContentType = "application/vnd.ms-excel";
            //curContext.Response.ContentEncoding = Encoding.UTF8;
            //curContext.Response.Charset = "";
            //string fullName = HttpUtility.UrlEncode("FileName.xls", Encoding.UTF8);
            string fullName = ".\\FileName.xlsx";
            // curContext.Response.AppendHeader("Content-Disposition",
            //     "attachment;filename=" + HttpUtility.UrlEncode(fullName, Encoding.UTF8));  //attachment后面是分号

            byte[] data = TableToExcel(dt, fullName).GetBuffer();
            File.WriteAllBytes(fullName, data);
            // curContext.Response.BinaryWrite(TableToExcel(dt, fullName).GetBuffer());
            // curContext.Response.End();
        }

        public MemoryStream TableToExcel(DataTable dt, string file)
        {
            //创建workbook
            IWorkbook workbook;
            string fileExt = Path.GetExtension(file).ToLower();
            if (fileExt == ".xlsx")
                workbook = new XSSFWorkbook();
            else if (fileExt == ".xls")
                workbook = new HSSFWorkbook();
            else
                workbook = null;
            //创建sheet
            ISheet sheet = workbook.CreateSheet("Sheet1");

            //表头
            IRow headrow = sheet.CreateRow(0);
            for (int i = 0; i < dt.Columns.Count; i++)
            {
                NPOI.SS.UserModel.ICell headcell = headrow.CreateCell(i);
                headcell.SetCellValue(dt.Columns[i].ColumnName);
            }
            sheet.SetColumnWidth(1, 60 * 256);

            //表内数据
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                IRow row = sheet.CreateRow(i + 1);
                for (int j = 0; j < dt.Columns.Count; j++)
                {
                    NPOI.SS.UserModel.ICell cell = row.CreateCell(j);
                    cell.SetCellValue(dt.Rows[i][j].ToString());
                }
            }

            //转化为字节数组
            MemoryStream ms = new MemoryStream();
            workbook.Write(ms);
            ms.Flush();

            return ms;
        }

        private void readToolStripMenuItem_Click(object sender, EventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog();
            ofd.InitialDirectory = Application.StartupPath;
            ofd.Filter = "Word文件|*.docx";
            ofd.Multiselect = true;
            string[] WordUrl;//数据源路径集合

            Dictionary<String, String> idNameDict = new Dictionary<string, string>();
            Dictionary<String, String> srcIdIdDict = new Dictionary<string, string>();

            
            DialogResult r = ofd.ShowDialog();
            if (r == DialogResult.OK)
            {
                WordUrl = ofd.FileNames;
            }
            else
            {
                return;
            }

            string wordFile = "";
            wordFile = WordUrl[0];
            Stream stream = File.OpenRead(wordFile);
            XWPFDocument doc = new XWPFDocument(stream);
            Regex regexReqName = new Regex(@"(?i)(?<=需求名称:\[)(.*)(?=\])");
            Regex regexReqId = new Regex(@"(?i)(?<=需求编号:\[)(.*)(?=\])");
            Regex regexReqSrc = new Regex(@"(?i)(?<=需求来源:\[)(.*)(?=\])");
            for (int i = 0; i < doc.Paragraphs.Count; i++)
            {
                var para = doc.Paragraphs[i];
                string text = para.ParagraphText; //获得文本
                if (text.Contains("名称"))
                {
                }
                var math = regexReqName.Match(text);
                if (math.Success)
                {
                     i++;
                   var paragraphId = doc.Paragraphs[i++];
                    var id = regexReqId.Match(paragraphId.ParagraphText);
                    if (!id.Success)
                    {
                        OutParseLog(math.Value, "Id解析错误"  +" - " + paragraphId.ParagraphText);
                        continue;
                    }
                    idNameDict[id.Value] = math.Value;
                   var paragraphSrc = doc.Paragraphs[i];
                    var srcId = regexReqSrc.Match(paragraphSrc.ParagraphText);
                    if (!srcId.Success)
                    {
                        OutParseLog(math.Value, "来源解析错误" + " - " + paragraphSrc.ParagraphText);
                        continue;
                    }
                    srcIdIdDict[id.Value] = srcId.Value;
                    OutInfo(math.Value, id.Value, srcId.Value);
                }

            }
         




        }

        private void OutInfo(string name, string id, string srcId)
        {
            this.textBox1.AppendText(String.Format("{0}\t{1}\t{2}\r\n", name,id,srcId));
        }

        private void OutParseLog(string name, string message)
        {
            this.textBox1.AppendText(String.Format("[{0}]{1}\r\n", name, message));
        }
    }
}
